class ListNode {
  constructor (val, next = null) {
    this.val = val;
    this.next = next;
  }
}
var MyLinkedList = function () {
  this.size = 0
  // 链表的头节点
  this.head = new ListNode
};

/** 
 * @param {number} index
 * @return {number}
 */
MyLinkedList.prototype.get = function (index) {
  if (index < 0 || index >= this.size) {
    return -1;
  }

  let curr = this.head;
  for (let i = 0; i < index; i++) {
    curr = curr.next;
  }

  return curr.val;
};

/** 
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtHead = function (val) {
  let newNode = new ListNode(val, this.head)
  this.head = newNode
  this.size++
};

/** 
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.addAtTail = function (val) {
  let cur = this.head
  let Node = new ListNode(val)
  if (cur === null) {
    this.head = Node
  } else {
    while (cur.next !== null) {
      cur = cur.next
    }
    cur.next = Node
  }
  this.size++
};

/** 
 * @param {number} index 
 * @param {number} val
 * @return {void}
 */
MyLinkedList.prototype.deleteAtIndex = function (index, val) {
  if (index < 0 || index >= this.size) {
    return;
  }

  if (index === 0) {
    this.head = this.head.next;
  } else {
    let curr = this.head;
    for (let i = 0; i < index - 1; i++) {
      curr = curr.next;
    }

    curr.next = curr.next.next;
  }

  this.size--;
};

/** 
 * @param {number} index
 * @return {void}
 */
MyLinkedList.prototype.addAtIndex = function (index) {
  if (index > this.size) {
    return;
  }

  if (index <= 0) {
    this.addAtHead(val);
    return;
  }

  if (index === this.size) {
    this.addAtTail(val);
    return;
  }

  let curr = this.head;
  for (let i = 0; i < index - 1; i++) {
    curr = curr.next;
  }

  const newNode = new Node(val, curr.next);
  curr.next = newNode;
  this.size++;
};
var obj = new MyLinkedList()
obj.addAtHead(6)
obj.addAtHead(7)
obj.addAtHead(10)
obj.addAtHead(3)
obj.addAtTail(4)
obj.addAtTail(5)
console.log(JSON.stringify(obj));

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * var obj = new MyLinkedList()
 * var param_1 = obj.get(index)
 * obj.addAtHead(val)
 * obj.addAtTail(val)
 * obj.addAtIndex(index,val)
 * obj.deleteAtIndex(index)
 */